// index.js
import { getCloudImage } from '../../utils/images';

const BANNER_ID = 'cloud://dp-6gydzcp27ac11774.6470-dp-6gydzcp27ac11774-1325695033/默认图片/bg3.webp';

Page({
  data: {
    //轮播数据
    banner:[],
    bannerImage:'',//背景图片
    loading: true,
    refreshTimer: null, 
    icons: [
      { name: 'food', icon: '/images/Four/food.png', text: '美食',url:'/pages/food/food'},
      { name: 'ecology', icon: '/images/Four/ecology-1.png', text: '生态',url:'/pages/ecology/ecology' },
      { name: 'base', icon: '/images/Four/cb-shifanjidi.png', text: '基地',url:'/pages/venues/venues' },
      { name: 'hero', icon: '/images/Four/people.png', text: '英烈',url:'/pages/hero/hero' }
    ],
    listData: [],    // 存储获取的数据
    loading: false   // 加载状态
  },

  async onLoad() {
    this.getRandomData() //主体内容
    // 获取背景图片
    const url = await getCloudImage(BANNER_ID);
    this.setData({ bannerImage: url });
  },

  // 轮播图跳转
  // 跳转到详情页面
  goToDetail(e) {
    const { item } = e.currentTarget.dataset;
    if (item.type === 'pois') {
      wx.navigateTo({
        url: `/pages/mapInfo/mapInfo?id=${item._id}`
      });
    } else if(item.type==='ecology'){
      wx.navigateTo({
        url: `/pages/ecology/ecology?name=${item.text}`
      });
    }else if(item.type === 'venue'){
      wx.navigateTo({
        url: `/pages/venuesInfo/venuesInfo?id=${item.id}`
      });
    }else if(item.type === 'food'){
      wx.navigateTo({
        url: `/pages/foodDetail/foodDetail?id=${item._id}`
      });
    }else if(item.type === 'story'){
      wx.navigateTo({
        url: `/pages/stroyDetail/stroyDetail?id=${item._id}`,
      })
    }
  },

  // 四大内容跳转
  onIconTap(event) {
    const url = event.currentTarget.dataset.url;
    console.log(url,'url');
    wx.navigateTo({
      url: url
    });
  },

  // 搜索跳转
  handleSearchFocus() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },

   // 主体获取随机数据
   getRandomData(callback) {
    this.setData({ loading: true })
  
    wx.showLoading({
      title: '数据加载中...',
      mask: true
    })

    wx.cloud.callFunction({
      name: 'getRandomIndex',
      success: res => {
        if (res.result.code === 200) {
          console.log('res.result',res.result);
          const categorized = res.result.data.reduce((acc, item) => {
            const typeKey = item.type?.toLowerCase().trim() || 'other'
            acc[typeKey] = acc[typeKey] || []
            acc[typeKey].push(item)
            return acc
          }, {})

          const firstItems = []
          Object.keys(categorized).forEach(type => {
            categorized[type][0] && firstItems.push(categorized[type][0])
          })

          this.setData({
            listData: categorized,
            banner: firstItems.map(item => ({
              ...item,
              img: item.img || item.image || item?.photos?.[0]?.url || item.food_image||'',
              name: item.name || item.text || item.className ||'未命名'
            }))
          })
        } else {
          this.showError('数据获取失败：' + res.result.message)
        }
      },
      fail: err => {
        console.error('云函数调用失败', err)
        this.showError('服务连接失败，请重试')
      },
      complete: () => {
        wx.hideLoading()
        this.setData({ loading: false })
        // 执行回调函数（停止下拉刷新）
        typeof callback === 'function' && callback()
      }
    })
  },



  // 错误处理
  showError(msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 3000
    })
  },

  // 新增下拉刷新处理
  onPullDownRefresh() {
    console.log('下拉');
    this.getRandomData(() => {
      wx.stopPullDownRefresh()
    })
  },


})




